package hy.iot.core.support;

import hy.iot.core.annotation.Endpoint;
import hy.iot.core.annotation.Mapping;
import hy.iot.core.handler.Handler;
import hy.iot.core.handler.SimpleHandler;
import hy.iot.core.utils.ClassUtils;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class EndpointScanSupport {

    private String packagesPath;
    private Map<String, Handler> endpointMap;

    public EndpointScanSupport(String packagesPath) {
        this.packagesPath = packagesPath;
        this.endpointMap = new HashMap<String, Handler>();
    }

    public Map<String, Handler> getEndpointMap() {
        List<Class> endpointClasses = ClassUtils.getClassList(packagesPath, Endpoint.class);
        for (Class endpointClass : endpointClasses) {
            try {
                Object bean = endpointClass.getDeclaredConstructor((Class[]) null).newInstance((Object[]) null);
                registerHandlers(bean);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
        return endpointMap;
    }

    /**
     * 将Endpoint中被@Mapping标记的方法注册到映射表
     */
    private synchronized void registerHandlers(Object bean) {
        Class<?> beanClass = bean.getClass();
        Method[] methods = beanClass.getDeclaredMethods();
        for (Method method : methods) {
            Mapping mapping = method.getAnnotation(Mapping.class);
            if (mapping != null) {
                String desc = mapping.desc();
                String[] types = mapping.pointType();
                Handler handler = new SimpleHandler(bean, method, desc, true);
                for (String type : types) {
                    endpointMap.put(type, handler);
                }
            }
        }
    }

}
